/*
 * @Author: Dufen~123 dufen.0
 * @Date: 2024-11-26 15:28:40
 * @LastEditors: Dufen~123 dufen.0
 * @LastEditTime: 2024-11-29 11:24:02
 * @FilePath: \my-app\src\components\commonTag\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { Tag, Space } from "antd";
import "../commonTag/index.css";
import { closeTab, changeCurrentMenu } from "../../store/reducers/tab";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

const CommonTag = () => {
  const tabList = useSelector((state) => state.tab.tabList);
  // console.log("tabList", tabList);
  const currentMenu = useSelector((state) => state.tab.currentMenu);
  const dispatch = useDispatch();
  const Navigate = useNavigate(); //跳转路由
  //关闭标签
  const handleClose = (tag) => {
    dispatch(closeTab(tag));
    const result = tabList.findIndex((item) => item.name == tag.name);
    console.log(result);
    if (result > 0) {
      // handleChange(tabList[result - 1]);//这一行和后面两行功能一样
      changeCurrentMenu(tabList[result - 1]);
      Navigate(tabList[result - 1].path);
    }
  };
  //切换标签
  const handleChange = (tag) => {
    //这里的tag就是下面传上来的item
    Navigate(tag.path);
    dispatch(changeCurrentMenu(tag));
  };
  //tag的显示。因为有两种标签，一种高亮一种不高亮，所以要用flag来标识高亮与否
  const setTag = (flag, item, index) => {
    return flag ? (
      <Tag
        color="#108ee9"
        closeIcon
        onClose={() => handleClose(item, index)}
        key={item.name}
      >
        {item.label}
      </Tag>
    ) : (
      <Tag onClick={() => handleChange(item)} key={item.name}>
        {item.label}
      </Tag>
    );
  };
  return (
    <Space className="common-tag" size={[0, 8]} wrap>
      {/* 如果要传参数就要写成回调函数的形式 */}
      {/* 面包屑的高亮与否和面包屑的内容是根据页面决定的，所有涉及到这个组件和aside组件的通信 */}
      {/* 遍历tabList来渲染面包屑 ，并且要有currentMenu才渲染*/}
      {currentMenu.name &&
        tabList.map((item, index) =>
          setTag(item.path === currentMenu.path, item, index)
        )}
    </Space>
  );
};

export default CommonTag;
